import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:labcloud_app/pages/uaa/login_register.dart';
import 'package:labcloud_app/models/user_model.dart';

class Profile extends StatefulWidget {
  const Profile({super.key});

  @override
  State<Profile> createState() => _ProfileState();
}

class _ProfileState extends State<Profile> {
  void _navigateToLoginRegister(BuildContext context) async {
    final result = await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => const LoginRegister(),
      ),
    );

    // 如果从登录页面返回了结果，刷新页面
    if (result != null) {
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    final userModel = Provider.of<UserModel>(context);

    return Scaffold(
      appBar: AppBar(
        title: const Text('个人页'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            const SizedBox(height: 50),
            // 头像
            CircleAvatar(
              radius: 50,
              backgroundImage: userModel.isLoggedIn && userModel.user != null
                ? NetworkImage(userModel.user!.avatarUrl ?? 'assets/images/default_avatar.png')
                : const AssetImage('assets/images/default_avatar.png'),
              // 如果没有默认头像，可以使用以下代码显示一个图标
              child: userModel.isLoggedIn 
                ? null 
                : const Icon(
                    Icons.person,
                    size: 50,
                    color: Colors.white,
                  ),
            ),
            const SizedBox(height: 20),
            // 用户名或未登录提示
            Text(
              userModel.isLoggedIn && userModel.user != null ? userModel.user!.nickname ?? '未知用户' : '未登录',
              style: const TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 30),

            // 功能按钮区域
            if (userModel.isLoggedIn) ...[
              Container(
                width: 300,
                padding: const EdgeInsets.all(10),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(15),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.grey.withOpacity(0.2),
                      spreadRadius: 1,
                      blurRadius: 5,
                      offset: const Offset(0, 3),
                    ),
                  ],
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    _buildFunctionButton(
                      icon: Icons.favorite,
                      label: '收藏夹',
                      onPressed: () {
                        // TODO: 跳转到收藏夹页面
                        ScaffoldMessenger.of(context).showSnackBar(
                          const SnackBar(content: Text('收藏夹功能待实现')),
                        );
                      },
                    ),
                    Container(
                      height: 40,
                      width: 1,
                      color: Colors.grey[300],
                    ),
                    _buildFunctionButton(
                      icon: Icons.location_on,
                      label: '收货地址',
                      onPressed: () {
                        // TODO: 跳转到收货地址页面
                        ScaffoldMessenger.of(context).showSnackBar(
                          const SnackBar(content: Text('收货地址功能待实现')),
                        );
                      },
                    ),
                    Container(
                      height: 40,
                      width: 1,
                      color: Colors.grey[300],
                    ),
                    _buildFunctionButton(
                      icon: Icons.account_balance_wallet,
                      label: '钱包',
                      onPressed: () {
                        // TODO: 跳转到钱包页面
                        ScaffoldMessenger.of(context).showSnackBar(
                          const SnackBar(content: Text('钱包功能待实现')),
                        );
                      },
                    ),
                  ],
                ),
              ),
            ],
            const SizedBox(height: 40),
            // 登录/注册按钮（合并为一个按钮）或退出登录按钮
            userModel.isLoggedIn
                ? ElevatedButton(
              onPressed: () {
                // 退出登录
                userModel.clearUser();
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.red,
                foregroundColor: Colors.white,
                padding: const EdgeInsets.symmetric(horizontal: 50, vertical: 15),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(30),
                ),
              ),
              child: const Text(
                '退出登录',
                style: TextStyle(
                  fontSize: 16,
                ),
              ),
            )
                : ElevatedButton(
              onPressed: () {
                _navigateToLoginRegister(context);
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.blue,
                foregroundColor: Colors.white,
                padding: const EdgeInsets.symmetric(horizontal: 50, vertical: 15),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(30),
                ),
              ),
              child: const Text(
                '登录/注册',
                style: TextStyle(
                  fontSize: 16,
                ),
              ),
            ),

          ],
        ),
      ),
    );
  }

  // 构建功能按钮
  Widget _buildFunctionButton({
    required IconData icon,
    required String label,
    required VoidCallback onPressed,
  }) {
    return GestureDetector(
      onTap: onPressed,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            icon,
            size: 28,
            color: Colors.blue,
          ),
          const SizedBox(height: 5),
          Text(
            label,
            style: const TextStyle(
              fontSize: 12,
              color: Colors.black87,
            ),
          ),
        ],
      ),
    );
  }
}